#coding=utf-8
import os, sys, datetime, time
os.environ['DJANGO_SETTINGS_MODULE'] = 'weibo.settings'
from weibo.tsina.models import Message, User

import tsina
today = datetime.date.today()
e = today.isoformat()
now = datetime.datetime.now()

logfile = '/home/jay/pvz.log'
l = open(logfile, 'a')
l.write('Tsina Robot started at %s\n'%now)
l.flush()

search_url = 'http://t.sina.com.cn/k/%s&page=%i'
reply = '荐下淘宝上超可爱的植物大战僵尸小东东 http://tsina.cndjango.com/1?own_id=%s'
keyword = '植物大战僵尸'

t = tsina.TsinaRobot(user='yanghaijiang2010@gmail.com', password='101783')
t.login()

n = t.search(keyword)
n = int(n)/50 + 1

for i in range(n):
  url = search_url%(keyword,i+1)
  now = datetime.datetime.now()
  code, r,c = t._fetch_url(url)
  ms = tsina.parse_search(c, now)
  
  for m in ms:
    d = m.created_at.date()
    if d < today:
      l.write('Tsina Robot quit\n')
      l.close()
      sys.exit()
    
    u, created = User.objects.get_or_create(user_id=m.own_id)
    mes, created2 = Message.objects.get_or_create(user=u, resource_id=m.resource_id, content=m.content, published_at=m.created_at)
    if (created2 and created):
      re_content = reply%m.own_id
      r,c = t.add_comment(m.own_id, m.resource_id, m.content, re_content)
      l.write('%s\t%s\t评论添加成功!\n'%(m.own_id, m.content))
      l.write('%s\n'%c)
      l.flush()
      time.sleep(10)        
      
